#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
重新分析第1阶段 - 专门查找第7个车型
基于分页指示器 "1-4 of 7" 的发现
"""

import json
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.common.exceptions import TimeoutException, NoSuchElementException

class Enhanced7CarAnalyzer:
    """增强版7车型分析器"""
    
    def __init__(self):
        self.setup_driver()
        self.all_discovered_cars = set()
        self.pagination_info = []
        
    def setup_driver(self):
        """设置Chrome WebDriver"""
        chrome_options = Options()
        chrome_options.add_argument('--disable-blink-features=AutomationControlled')
        chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
        chrome_options.add_experimental_option('useAutomationExtension', False)
        chrome_options.add_argument('--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15')
        
        service = Service(ChromeDriverManager().install())
        self.driver = webdriver.Chrome(service=service, options=chrome_options)
        self.wait = WebDriverWait(self.driver, 10)
    
    def analyze_7_cars_logic(self):
        """重新分析，专门查找第7个车型"""
        try:
            print("🔍 重新分析第1阶段 - 专门查找第7个车型")
            print("🎯 重点关注分页指示器和轮播逻辑")
            
            # 访问页面
            url = "https://www.ford.co.uk/shop/build-your-ford/ngc2/ice2/model?catalogId=WAEGB-CGE-2022-FocusMCAGBR202450&series=ACMAA_VS-D3&paint=PN4A7&planId=c"
            print(f"\n📖 访问页面: {url}")
            
            self.driver.get(url)
            time.sleep(5)
            
            # 处理Cookie
            self.handle_cookies_quick()
            
            # 分析分页信息
            print(f"\n📊 步骤1: 分析分页指示器")
            self.analyze_pagination_indicator()
            
            # 分析轮播按钮状态
            print(f"\n🎮 步骤2: 分析轮播按钮状态")
            self.analyze_carousel_buttons()
            
            # 系统性地遍历所有页面
            print(f"\n🔄 步骤3: 系统性遍历所有车型页面")
            self.systematic_car_discovery()
            
            # 最终验证
            print(f"\n✅ 步骤4: 最终验证和总结")
            self.final_verification()
            
            return True
            
        except Exception as e:
            print(f"❌ 分析过程出错: {e}")
            return False
        finally:
            input("按Enter键关闭浏览器...")
            self.driver.quit()
    
    def handle_cookies_quick(self):
        """快速处理Cookie"""
        try:
            cookie_containers = self.driver.find_elements(By.CSS_SELECTOR, '[class*="cookie"], [class*="Cookie"], [class*="consent"]')
            for container in cookie_containers:
                try:
                    if container.is_displayed():
                        self.driver.execute_script("arguments[0].style.display = 'none';", container)
                except:
                    pass
            print("✓ Cookie处理完成")
        except Exception as e:
            print(f"Cookie处理出错: {e}")
    
    def analyze_pagination_indicator(self):
        """分析分页指示器 - 寻找 "1-4 of 7" 类型的文本"""
        try:
            # 查找分页指示器的可能位置
            pagination_selectors = [
                # 在按钮之间的文本
                '.PaginationArrowBtn-sc-1o074yf-0 ~ *',
                '[class*="pagination"] *',
                '[class*="Pagination"] *',
                # 可能包含数字范围的元素
                '*[text()[contains(., "of")]]',
                # 查找所有包含数字模式的文本
                '*[text()[matches(., "\\d+-\\d+ of \\d+")]]'
            ]
            
            pagination_found = False
            
            # 首先尝试在按钮附近查找
            try:
                next_button = self.driver.find_element(By.CSS_SELECTOR, 'button[action="next"]')
                prev_button = self.driver.find_element(By.CSS_SELECTOR, 'button[action="prev"]')
                
                # 获取两个按钮的父容器
                parent_container = next_button.find_element(By.XPATH, '..')
                
                print(f"  🔍 在按钮容器中查找分页信息...")
                container_text = parent_container.text
                print(f"    容器文本: '{container_text}'")
                
                # 检查是否包含 "of" 模式
                if 'of' in container_text.lower():
                    pagination_found = True
                    self.pagination_info.append(container_text)
                    print(f"  ✅ 找到分页指示器: {container_text}")
                
            except Exception as e:
                print(f"  在按钮容器中查找失败: {e}")
            
            # 如果没找到，扩大搜索范围
            if not pagination_found:
                print(f"  🔍 扩大搜索范围...")
                
                # 查找所有可能包含分页信息的元素
                all_elements = self.driver.find_elements(By.XPATH, "//*[contains(text(), 'of') or contains(text(), 'Of')]")
                
                for element in all_elements:
                    if element.is_displayed():
                        element_text = element.text.strip()
                        if element_text and ('of' in element_text.lower()):
                            print(f"    可能的分页信息: '{element_text}'")
                            self.pagination_info.append(element_text)
                            pagination_found = True
            
            # 如果还是没找到，尝试查找数字模式
            if not pagination_found:
                print(f"  🔍 查找数字模式...")
                import re
                
                page_source = self.driver.page_source
                # 查找 "数字-数字 of 数字" 模式
                pattern = r'\d+-\d+\s+of\s+\d+'
                matches = re.findall(pattern, page_source)
                
                if matches:
                    for match in matches:
                        print(f"    找到数字模式: '{match}'")
                        self.pagination_info.append(match)
                        pagination_found = True
                
            if not pagination_found:
                print(f"  ⚠️  未找到明显的分页指示器")
            
        except Exception as e:
            print(f"  ❌ 分析分页指示器时出错: {e}")
    
    def analyze_carousel_buttons(self):
        """详细分析轮播按钮状态"""
        try:
            # 查找下一页按钮
            next_buttons = self.driver.find_elements(By.CSS_SELECTOR, 'button[action="next"]')
            prev_buttons = self.driver.find_elements(By.CSS_SELECTOR, 'button[action="prev"]')
            
            print(f"  找到 {len(next_buttons)} 个下一页按钮")
            print(f"  找到 {len(prev_buttons)} 个上一页按钮")
            
            for i, button in enumerate(next_buttons):
                aria_disabled = button.get_attribute('aria-disabled')
                aria_label = button.get_attribute('aria-label')
                class_name = button.get_attribute('class')
                
                print(f"    下一页按钮 {i+1}:")
                print(f"      aria-disabled: {aria_disabled}")
                print(f"      aria-label: {aria_label}")
                print(f"      class: {class_name}")
            
            for i, button in enumerate(prev_buttons):
                aria_disabled = button.get_attribute('aria-disabled')
                aria_label = button.get_attribute('aria-label')
                class_name = button.get_attribute('class')
                
                print(f"    上一页按钮 {i+1}:")
                print(f"      aria-disabled: {aria_disabled}")
                print(f"      aria-label: {aria_label}")
                print(f"      class: {class_name}")
                
        except Exception as e:
            print(f"  ❌ 分析轮播按钮时出错: {e}")
    
    def systematic_car_discovery(self):
        """系统性地发现所有车型"""
        try:
            max_iterations = 10  # 防止无限循环
            iteration = 0
            
            while iteration < max_iterations:
                iteration += 1
                print(f"\n  🔄 第 {iteration} 轮探索:")
                
                # 获取当前状态
                current_cars = self.get_current_cars()
                
                # 记录新发现的车型
                new_cars = []
                for car in current_cars:
                    if car['data_cy'] not in self.all_discovered_cars:
                        new_cars.append(car)
                        self.all_discovered_cars.add(car['data_cy'])
                
                if new_cars:
                    print(f"    ✓ 新发现 {len(new_cars)} 个车型:")
                    for car in new_cars:
                        visibility = "可见" if car['visible'] else "隐藏"
                        print(f"      - {car['data_cy']}: {visibility}")
                else:
                    print(f"    - 本轮未发现新车型")
                
                print(f"    📊 累计发现车型: {len(self.all_discovered_cars)} 个")
                print(f"    📊 当前页面车型: {len(current_cars)} 个")
                
                # 分析分页信息变化
                self.analyze_pagination_indicator()
                
                # 尝试点击下一页
                if self.click_next_if_available():
                    print(f"    ✓ 成功点击下一页")
                    time.sleep(2)
                else:
                    print(f"    ❌ 无法点击下一页，可能已到最后")
                    break
                
                # 如果发现了7个车型，可以停止
                if len(self.all_discovered_cars) >= 7:
                    print(f"    🎉 已发现 {len(self.all_discovered_cars)} 个车型，达到预期!")
                    break
            
            print(f"\n  📊 系统性探索完成:")
            print(f"    - 总轮次: {iteration}")
            print(f"    - 发现车型: {len(self.all_discovered_cars)} 个")
            print(f"    - 车型列表: {list(self.all_discovered_cars)}")
            
        except Exception as e:
            print(f"  ❌ 系统性车型发现时出错: {e}")
    
    def get_current_cars(self):
        """获取当前页面的所有车型"""
        try:
            elements = self.driver.find_elements(By.CSS_SELECTOR, 'div[data-cy][class*="ProductTile"]')
            cars = []
            
            for element in elements:
                data_cy = element.get_attribute('data-cy')
                if data_cy:
                    car_info = {
                        'data_cy': data_cy,
                        'visible': element.is_displayed(),
                        'element': element
                    }
                    cars.append(car_info)
            
            return cars
        except Exception as e:
            print(f"    获取当前车型时出错: {e}")
            return []
    
    def click_next_if_available(self):
        """如果可用，点击下一页按钮"""
        try:
            next_button = self.driver.find_element(By.CSS_SELECTOR, 'button[action="next"]')
            
            # 检查按钮是否可用
            aria_disabled = next_button.get_attribute('aria-disabled')
            
            if aria_disabled == 'false':
                self.driver.execute_script("arguments[0].click();", next_button)
                return True
            else:
                print(f"    下一页按钮已禁用 (aria-disabled={aria_disabled})")
                return False
                
        except Exception as e:
            print(f"    点击下一页按钮时出错: {e}")
            return False
    
    def final_verification(self):
        """最终验证和总结"""
        try:
            print(f"\n  📋 最终验证结果:")
            print(f"    - 期望车型数: 7")
            print(f"    - 实际发现数: {len(self.all_discovered_cars)}")
            print(f"    - 分页信息: {self.pagination_info}")
            
            if len(self.all_discovered_cars) == 7:
                print(f"  ✅ 成功！找到了所有7个车型")
                success = True
            else:
                print(f"  ⚠️  车型数量仍不符合预期")
                success = False
            
            print(f"\n  📝 发现的车型列表:")
            for i, car_name in enumerate(sorted(self.all_discovered_cars), 1):
                print(f"    {i}. {car_name}")
            
            if self.pagination_info:
                print(f"\n  📄 分页指示器信息:")
                for info in self.pagination_info:
                    print(f"    - {info}")
            
            # 保存详细结果
            result = {
                "analysis_time": time.strftime("%Y-%m-%d %H:%M:%S"),
                "expected_cars": 7,
                "discovered_cars": len(self.all_discovered_cars),
                "car_list": list(self.all_discovered_cars),
                "pagination_info": self.pagination_info,
                "success": success
            }
            
            with open('enhanced_7car_analysis.json', 'w', encoding='utf-8') as f:
                json.dump(result, f, indent=2, ensure_ascii=False)
            
            print(f"\n💾 详细结果已保存到 enhanced_7car_analysis.json")
            
            return success
            
        except Exception as e:
            print(f"  ❌ 最终验证时出错: {e}")
            return False

def main():
    """主函数"""
    analyzer = Enhanced7CarAnalyzer()
    success = analyzer.analyze_7_cars_logic()
    
    if success:
        print("\n🎉 第7个车型发现分析完成！")
    else:
        print("\n❌ 第7个车型发现分析失败！")

if __name__ == "__main__":
    main()
